import util from "../../../utils/util.js";
import api from "../../../common/api.js";
import {
  xstShare
} from "../../../common/subscribe.js";
import {
  insertHouseMaterialDownLoadLog
} from "../../../common/log.js";
import constant from "../../../common/constant.js";
import {
  menuHandler
} from "../../../common/menuHandler.js";
import {
  IMG_COMPOUND_VIDEO,
  VIP_MESSAGE
} from "../../../common/menuId.js";
import {
  httpUrlCheck
} from "../../../utils/utilsNew.js";
const config = require("../../../utils/config.js");

const app = getApp();
/** gio埋点 */
const _map = {
  NEWHOUSE: constant.XIN_FANG,
  RENT: constant.CHU_ZU,
  SALES: constant.ER_SHOU,
};
const _constant = {
  TAB_MANAGE: 'manage',
  TAB_INFO: 'info',
  TAB_DEVELOPMENT: 'development',
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isShowFormHouseTrack: false, // 房源轨迹表单弹窗开关
    isTrackListMore: true, // 房源轨迹是否有更多
    _trackListIndex: 0, // 房源轨迹当前页
    _trackListSize: 10, // 房源轨迹每页数量
    houseTrackList: [], // 房源轨迹列表
    isShowVisitor: true, // 顶部访客折叠开关
    _autoCallLandlordFlag: false, // 是否自动开启联系房东标记
    landlordList: [], // 房东电话列表
    currentLandlordInfo: {}, // 当前编辑房东信息
    isShowFormLandlord: false, // 房东手机号表单弹窗开关
    houdelid: "", //房源ID
    houseTypes: "", // 房源类型 二手 出租
    loading: true,
    defaultTabSelect: '',
    tabSelect: '',
    tabOptions: [{
      id: _constant.TAB_MANAGE,
      label: '房源管理',
      add: '',
    }, {
      id: _constant.TAB_INFO,
      label: '房源信息',
      add: '',
    }, {
      id: _constant.TAB_DEVELOPMENT,
      label: '房源情报',
      add: '',
    }],
    visitorCount: 0, // 访客数量
    reason: "", // 下架理由
    time: "", // 下架时间
    vrUrl: "", // 视频链接
    vr: false, // 是否有vr
    vrdown: false, // vr下载状态
    vrTab: 1, // 轮播图当前tab
    currentSwiper: 0, // 轮播图当前图片
    tagName: "", // 轮播图标签
    detailContent: "", // 房源详情
    currentTabState: 0, // 当前地图tab
    tabList: config.tabList, // 地图tab
    markers: [], // 地图点位
    cooperationId: '',
    fn: "", // 对应的会员功能

    shareShowDialog: false, // 分享btn弹窗
    // friendsShowDialog: false,
    pyqVisible: false, // 点击朋友圈分享后的弹窗
    // pyqmodal: false, // 点击朋友圈分享后的弹窗

    isLoadHouseDone: false, // 视频下载完成
    isLoadingHouse: false, // 下载视频中
    videoOption: false, // 下载视频的弹窗
    menuId: "", // 操作的权限按钮
    // moreOption: false, // 更多功能开关
    // showMoreOptions: false, // 更多功能开关
    // moreDownload: false, // 下载房源素材
    isUpdate: false, // 有没有修改房源详情

    memberOption: false, // 不确定作用
    // listTabShowDialog: false,
    // widthVi: app.globalData.windowHeight,
    // showDialog: false,
    // contactShowDialog: false,
    // copyText: "",
    // shorturlL: "",
    userInfo: '', //合作房源---个人房源--底部操作栏 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("###details options###", options);
    wx.hideShareMenu()
    wx.showLoading({
      title: '加载中...',
    })
    setTimeout(() => {
      wx.hideLoading()
    }, 1000)
    app.globalData.loginPromise.then(() => {
      this.setData({
        tabSelect: options.tab || _constant.TAB_INFO,
        defaultTabSelect: options.tab || _constant.TAB_INFO,
        source: options.from || '', // 0:搬家 1:首页列表、获客 2:合作房源
        houdelid: options.houdelid || '',
        houseTypes: options.type || '',
        cooperationId: options.cooperation || ''
      })
      this.loadVisitorCount()
      this.getHouseInfo();
      this.getOverAllUserData()
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    var houdelid = wx.getStorageSync("houdelid");
    if (houdelid == "1") {
      wx.removeStorageSync("houdelid");
      this.setData({
        shareShowDialog: !this.data.shareShowDialog,
      });
    }

    if (houdelid == "3") {
      wx.removeStorageSync("houdelid");
      this.setData({
        shareShowDialog: !this.data.shareShowDialog,
      });
    }

    if (this.data.isUpdate) {
      this.getHouseInfo();
    }

    this.setData({
      currentTabState: app.globalData.mapTabStatusIndex,
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this;
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    prevPage && prevPage.setData({
      isUpdate: true,
    });
    try {
      const type = that.data.detailContent.houDelVO.delegationType;
      if (type == "SALES") {
        wx.setStorageSync("currentStatus", 1);
      } else if (type == "RENT") {
        wx.setStorageSync("currentStatus", 2);
      }
    } catch (error) {}
    wx.setStorageSync("boole", false);
    var houdelid = wx.getStorageSync("houdelid");
    if (houdelid == "2") {
      console.log("这里的问题=====");
      wx.removeStorageSync("houdelid");
      wx.navigateBack({
        delta: 2,
      });
    }
    app.globalData.mapTabStatusIndex = 0;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 页面滚动
   */
  onPageScroll(e) {
    const {
      isShowVisitor
    } = this.data
    if (e.scrollTop > 2 && isShowVisitor) {
      this.setData({
        isShowVisitor: false,
      })
    }
    if (e.scrollTop < 2 && !isShowVisitor) {
      this.setData({
        isShowVisitor: true,
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    const {
      detailContent,
      cooperationId
    } = this.data
    const {
      houImageVO,
      houDelVO
    } = detailContent || {}
    let buildSize = houDelVO.buildSize ? houDelVO.buildSize + '㎡' : '';
    let price = houDelVO.delegationType === "SALES" ? `${houDelVO.totalPrices ? houDelVO.totalPrices / 10000 : 0}` : `${houDelVO.totalPrices || 0}`
    let unit = houDelVO.delegationType === "SALES" ? '万' : '元/月'
    let userId = getApp().globalData.sessionUser.id
    return {
      title: `${houDelVO.resblockName || ''} ${houDelVO.room || 0}室${houDelVO.hall || 0}厅 ${buildSize} ${price ? price + unit : ''}`,
      path: `/pages/house/RentalHouseDetail/teamworkHouseDetail/teamworkHouseDetail?cooperationId=${cooperationId}&agentId=${userId}`,
      imageUrl: houImageVO && houImageVO.length ? houImageVO[0].url : '',
    }
  },

  // 访客数量
  loadVisitorCount() {
    api.getCount({
      houDelId: this.data.houdelid,
    }, (res) => {
      this.setData({
        visitorCount: res.data.content || 0,
      });
    });
  },

  // 跳转访客列表
  onJumpVisitor() {
    wx.navigateTo({
      url: `/pages/visitors/visitors?id=${this.data.detailContent.houDelVO.id}`,
    });
  },

  // 轮播tab点击
  checkVr(e) {
    this.setData({
      vrTab: e.currentTarget.dataset.tabvr,
      currentSwiper: 0,
    });
  },

  // 轮播图改变
  swiperChange(e) {
    const that = this,
      currentSwiper = e.detail.current;
    const tagName = that.data.detailContent.houImageVO[currentSwiper].tagName;
    this.setData({
      currentSwiper: currentSwiper,
      tagName: tagName,
    });
  },

  // 预览轮播图
  previewBannerImage: function (e) {
    var bannerList = this.data.bannerList,
      current = bannerList[this.data.currentSwiper];
    wx.previewImage({
      current: current,
      urls: bannerList,
    });
  },

  // 切换tab
  onTabChange(e) {
    const {
      tabSelect
    } = this.data
    let target = e.detail
    if (tabSelect === target) return
    this.setData({
      tabSelect: target,
    })
  },

  // 获取房源详情
  getHouseInfo() {
    const {
      houdelid,
      cooperationId,
      currentSwiper,
      source
    } = this.data
    api.getHouseInfo({
      houDelId: houdelid,
    }, (res) => {
      if (res && res.data && res.data.errorCode === '21007') {
        wx.showModal({
          title: '提示',
          content: '该房源被删除，无法查看',
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              wx.navigateBack({
                delta: 1,
              })
            }
          }
        })
        return
      }

      const content = res.data.content;
      let bannerList = [];
      let reason = ''

      for (var k in content.houImageVO) {
        bannerList.push(content.houImageVO[k].url);
      }

      let reasonOptions = {
        0: '由我出售',
        1: '由他人出售',
        2: '业主不卖了',
        3: '由我出租',
        4: '由他人出租',
        5: '业主不租了',
        6: '其他原因停止交易',
      }
      if (content.houDelVO.reason && content.houDelVO.reason.trim) {
        reason = reasonOptions[content.houDelVO.reason.trim()]
      }

      this.setData({
        markers: [{
          id: 0,
          latitude: content.houDelVO.lat,
          longitude: content.houDelVO.lng,
          title: content.houDelVO.resblockName,
        }, ],
        bannerList: bannerList,
        detailContent: content,
        tagName: content.houImageVO.length > 0 ? content.houImageVO[currentSwiper].tagName : "",
        loading: false,
        time: content.houDelVO.changeTime ? util.dateFormat(new Date(content.houDelVO.changeTime), "yyyy-MM-dd") : '',
        reason: content.houDelVO.downReason || reason || '',
        vr: (content.hmDelSummaryInfo.houSubType == 1 && content.hmDelSummaryInfo.houSubTypeState == 10) ||
          (content.hmDelSummaryInfo.houSubType == 1 && content.hmDelSummaryInfo.houSubTypeState == 1) ?
          true : false,

        vrdown: content.hmDelSummaryInfo.houSubType == 1 &&
          (content.hmDelSummaryInfo.houSubTypeState == 0 || content.hmDelSummaryInfo.houSubTypeState == -1) ?
          true : false,
      });
      if (source === '2') {
        wx.showShareMenu({
          withShareTicket: true,
        });
      }
      if (content.hmDelSummaryInfo.videoMaterial) {
        this.getOssfiles();
      }
      // 加载房东列表
      this.getLandlordPhone()
      // 加载/刷新 房源轨迹
      this.refreshHouseTrack()
      // 日志
      wx.gio("setPage", {
        [constant.ROOM_TYPE_PVAR]: _map[content.houDelVO.delegationType],
      });
      this.uploadVisitorLog({
        cooperationId: cooperationId,
        delId: houdelid
      })
    });
  },

  // 访客日志
  uploadVisitorLog({
    cooperationId,
    delId
  }) {
    const {
      source
    } = this.data
    if (source !== '2') return
    api.addVisitor({
      cooperationId,
      delId
    }, (res) => {})
  },

  // 跳转地图详情
  goMapDetails(e) {
    const currentTitle = e.currentTarget.dataset.title;
    const currentTabState = e.currentTarget.dataset.index;
    const lat = this.data.detailContent.houDelVO.lat;
    const lng = this.data.detailContent.houDelVO.lng;
    this.setData({
      currentTabState,
    });
    wx.navigateTo({
      url: `/pages/house/RentalHouseDetail/mapDetails/mapDetails?latitude=${lat}&longitude=${lng}&currentTitle=${currentTitle}&currentTabState=${currentTabState}`,
    });
  },

  // 跳转系统地图
  handleNavigation() {
    const lat = this.data.detailContent.houDelVO.lat;
    const lng = this.data.detailContent.houDelVO.lng;
    wx.openLocation({
      latitude: Number(lat),
      longitude: Number(lng),
      scale: 16,
    });
  },

  // 分享弹窗开关
  toggleShareTabDialog() {
    this.setData({
      shareShowDialog: !this.data.shareShowDialog,
      // friendsShowDialog: false,
      // pyqmodal: false,
    });
    if (this.data.shareShowDialog) {
      // 小神推
      xstShare();
    }
  },

  // 直接分享----到树懒找房小程序---带各种ID 和房源详情的相关数据
  goShareImage() {
    var allId = {};
    var loginUserInfo = getApp().globalData.loginUserInfo;
    if (loginUserInfo) {
      allId.agentId = loginUserInfo.data.content.sessionUser.id;
      allId.storeId = loginUserInfo.data.content.sessionUser.extProps.storeId;
      allId.mkId = "EMP";
      allId.houDelId = this.data.detailContent.houDelVO.id;
    }

    api.shareHouseLog({
      sourceApp: "0",
      shareType: "1",
      delId: this.data.detailContent.houDelVO.id,
    });

    wx.gio("track", constant.HANDLE_SHARE, {
      [constant.ROOMTYPE_VAR]: _map[this.data.detailContent.houDelVO.delegationType],
      [constant.SHARETYPE_VAR]: constant.ZJ_SHARE,
      [constant.SHARESOURCE_VAR]: constant.DETAILS_SHARE,
    });

    let extraData = {
      allId: allId,
      type: "coupon",
    };
    extraData.allId.isTranspond = true;
    wx.navigateToMiniProgram({
      appId: "wx5adc5dd9870f6a26", //树懒找房极速版appid
      path: "pages/houseShare/RentalHouseDetailLite/RentalHouseDetailLite?jingjiId=" + JSON.stringify(extraData),
      extraData: extraData,
      envVersion: util.envVersion,
      success: (res) => {
        wx.gio("track", constant.SHARE_SUCCESS, {
          [constant.ROOMTYPE_VAR]: _map[this.data.detailContent.houDelVO.delegationType],
          [constant.SHARETYPE_VAR]: constant.ZJ_SHARE,
        });
      },
      fail(res) {},
    });
  },

  // 海报分享
  posterShareImage() {
    api.shareHouseLog({
      sourceApp: "0",
      shareType: "3",
      delId: this.data.detailContent.houDelVO.id,
    });

    wx.gio("track", constant.HANDLE_SHARE, {
      [constant.ROOMTYPE_VAR]: _map[this.data.detailContent.houDelVO.delegationType],
      [constant.SHARETYPE_VAR]: constant.HB_SHARE,
      [constant.SHARESOURCE_VAR]: constant.DETAILS_SHARE,
    });

    var allId = {};
    var loginUserInfo = getApp().globalData.loginUserInfo;
    const sessionUser = loginUserInfo.data.content.sessionUser;
    allId.agentId = sessionUser.id;
    allId.storeId = sessionUser.extProps.storeId;
    allId.mkId = "EMP";
    allId.houDelId = this.data.detailContent.houDelVO.id;
    allId.realName = sessionUser.realName;
    allId.mobile = sessionUser.mobile;
    allId.wxHeadImg = sessionUser.avatar || sessionUser.extProps.wxHeadImg;

    var extraData = {
      roomDetail: this.data.detailContent,
      allId: allId,
      type: "coupon",
    };

    extraData = JSON.parse(JSON.stringify(extraData));
    Object.assign(extraData.roomDetail, extraData.roomDetail.houDelVO);
    extraData.roomDetail.houDelVO = null;
    app.globalData.houseShareBannerInfo = extraData;
    console.log("app.globalData.houseShareBannerInfo==", app.globalData.houseShareBannerInfo);
    wx.navigateTo({
      url: "/pages/house/RentalHouseDetail/oldHouseShare/oldHouseShare"
    });

    wx.gio("track", constant.SHARE_SUCCESS, {
      [constant.ROOMTYPE_VAR]: _map[this.data.detailContent.houDelVO.delegationType],
      [constant.SHARETYPE_VAR]: constant.HB_SHARE,
    });
  },

  // 分享到朋友圈，复制关键信息及链接
  goSharepyq() {
    api.shareHouseLog({
      sourceApp: "0",
      shareType: "2",
      delId: this.data.detailContent.houDelVO.id,
    });

    wx.gio("track", constant.HANDLE_SHARE, {
      [constant.ROOMTYPE_VAR]: _map[this.data.detailContent.houDelVO.delegationType],
      [constant.SHARETYPE_VAR]: constant.PYQ_SHARE,
      [constant.SHARESOURCE_VAR]: constant.DETAILS_SHARE,
    });

    const houDelVO = this.data.detailContent.houDelVO;
    const priceTitle = houDelVO.delegationType == "SALES" ? '售价' : '租金';
    let price =
      houDelVO.totalPrices == -1 ?
      "暂无售价" :
      houDelVO.delegationType == "SALES" ?
      houDelVO.totalPrices / 10000 + "万" :
      houDelVO.totalPrices + "元/月";
    wx.setClipboardData({
      data: `小区：${houDelVO.resblockName}
  户型：${
          houDelVO.room == -1 && houDelVO.hall
            ? "暂无户型"
            : houDelVO.room + "室" + houDelVO.hall + "厅"
        }
  面积：${
          houDelVO.buildSize == -1
            ? "暂无面积"
            : houDelVO.buildSize + "m²"
        }
  ${priceTitle}：${price}
  地址：${houDelVO.area ? houDelVO.area + " " : ""}${
          houDelVO.addr
        }`,
      success(res) {
        wx.getClipboardData({
          success(res) {},
        });
      },
    });
    this.setData({
      shareShowDialog: true,
      // friendsShowDialog: true,
      pyqVisible: true,
    });
    var loginUserInfo = getApp().globalData.loginUserInfo;
    api.oldHouseInfo({
      agentid: loginUserInfo.data.content.sessionUser.id,
      openid: wx.getStorageSync("aldstat_op"),
    });
  },

  // 朋友圈分享关闭弹窗
  friendsShareTabDialog() {
    this.setData({
      shareShowDialog: false,
      // friendsShowDialog: false,
      // pyqmodal: false,
      pyqVisible: false,
    });
  },

  // -----------------------------更多功能------------------------------------

  onClickMaterial(e) {
    switch (e.detail) {
      case 'COPY_VR':
        this.copyVrUrl()
        break;
      case 'VIDEO_VOICE':
        this.goToVoice()
        break;
      case 'DOWNLOAD_VR':
        this.handleMemberDownLoadImgs({
          currentTarget: {
            dataset: {
              id: 'f18a0d92aec4499f8866cff3d7226c47',
              enable: true
            }
          }
        })
        break;
      case 'COMPOUND_PANORAMA':
        this.handleMemberDownLoadImgs({
          currentTarget: {
            dataset: {
              id: '60e6298af0b24f9db9af005e11e8e87a',
              enable: true
            }
          }
        })
        break;
      case 'VR_TO_VIDEO':
        this.handleMemberDownLoadImgs({
          currentTarget: {
            dataset: {
              id: 'cb97dc7641fc482c805d42f83661c1c0',
              enable: true
            }
          }
        })
        break;
      case 'DOWNLOAD_PANORAMA':
        this.handleMemberDownLoadImgs({
          currentTarget: {
            dataset: {
              id: '73ed001b790d4d1cb3e1f74a88756669',
              enable: true
            }
          }
        })
        break;
      case 'DOWNLOAD_VIDEO':
        this.handleMemberDownLoadImgs({
          currentTarget: {
            dataset: {
              id: '5a634e15be20415c854056e30e49545d',
              enable: true
            }
          }
        })
        break;
      case 'DOWNLOAD_IMG':
        this.handleMemberDownLoadImgs({
          currentTarget: {
            dataset: {
              id: '4c75216b479d4ba894e35e14549ca355',
              enable: true
            }
          }
        })
        break;
        // 图片转视频
      case 'IMG_TO_VIDEO':
        this.handleMemberDownLoadImgs({
          currentTarget: {
            dataset: {
              id: IMG_COMPOUND_VIDEO,
              enable: true
            }
          }
        })
        break;
    }
  },

  // 隐藏更多功能弹窗
  // handleHideMoreOptions() {
  //   this.setData({
  //     showMoreOptions: false,
  //     moreOption: false,
  //     moreDownload: false,
  //     memberOption: false,
  //   });
  // },

  // 展示更多功能弹窗
  // handleMoreOptions() {
  //   this.setData({
  //     showMoreOptions: true,
  //     moreOption: true,
  //   });
  // },

  // 展示下载素材弹窗
  // handleMoreDownload() {
  //   this.setData({
  //     showMoreOptions: true,
  //     moreDownload: true,
  //   });
  // },

  // 查询是否有功能权限
  handleMemberDownLoadImgs(e) {
    let menuId = e.currentTarget.dataset.id;
    let enable = e.currentTarget.dataset.enable;
    if (!enable) return;

    this.setData({
      fn: VIP_MESSAGE[menuId],
    });
    menuHandler
      .call(this, menuId)
      .then((downLoadImgs) => {
        this.setData({
          releaseNumber: downLoadImgs.dayNumber,
          totalNumber: downLoadImgs.totalNumber,
          menuId,
          dayNumbered: downLoadImgs.dayNumbered,
          totalNumbered: downLoadImgs.totalNumbered,
          statue: downLoadImgs.statue,
        });
        switch (menuId) {
          case "4c75216b479d4ba894e35e14549ca355":
            this.hanldeDownLoadImgs();
            break;
          case "73ed001b790d4d1cb3e1f74a88756669":
            this.goToPanoramagram();
            break;
          case "f18a0d92aec4499f8866cff3d7226c47":
            this.vrDownLoad();
            break;
          case "60e6298af0b24f9db9af005e11e8e87a":
            this.goToComposite();
            break;
          case "5a634e15be20415c854056e30e49545d":
            this.handleVideo();
            break;
          case IMG_COMPOUND_VIDEO:
            this.goToVideo();
            break;
        }
      })
      .catch(() => {
        console.log(`不能使用${VIP_MESSAGE[menuId]}`);
      });
  },

  // 下载房源图片
  hanldeDownLoadImgs(e) {
    this.hanldedownLoadImgs();
  },

  // 下载房源图片
  hanldedownLoadImgs() {
    insertHouseMaterialDownLoadLog({
      logType: "0",
      delId: this.data.detailContent.houDelVO.id,
    });

    // this.handleHideMoreOptions();
    if (this.data.bannerList && this.data.bannerList.length) {
      let list = [...this.data.bannerList];
      let total = list.length;
      let count = 0;
      wx.showLoading({
        title: `保存中${count}/${total}`,
      });
      let save = () => {
        this.saveImageAndroid(list.shift()).then(() => {
          wx.showLoading({
            title: `保存中${++count}/${total}`,
          });

          if (list.length) {
            save();
          } else {
            setTimeout(() => {
              wx.hideLoading();
              wx.showToast({
                title: "图片已保存至手机相册",
                icon: "none",
              });
              api.getMemberPower({
                menuId: "4c75216b479d4ba894e35e14549ca355"
              }, (res) => {
                if (res.data.isSuccess) {
                  wx.setStorageSync("memberInfo", res.data.content.rows);
                }
              });
            }, 200);
          }
        });
      };
      save();
    }
  },

  // 下载房源图片(安卓)
  saveImageAndroid(img) {
    return new Promise((resolve, reject) => {
      let filePath = wx.env.USER_DATA_PATH + "/" + Date.now() + ".jpg";
      wx.downloadFile({
        url: img,
        filePath,
        success: ({
          filePath
        }) => {
          wx.saveImageToPhotosAlbum({
            filePath,
            success: () => {
              resolve();
              // 删除缓存
              let fileMgr = wx.getFileSystemManager();
              fileMgr.unlink({
                filePath,
                success: function (r) {
                  console.log("删除缓存ok", r);
                },
              });
            },
            fail: (err) => {
              console.log("保存图片失败", err, filePath);
              resolve();
            },
          });
        },
        fail: () => {
          console.log("读取图片信息失败", err);
          resolve();
        },
      });
    });
  },

  // 跳转合成视频
  goTovideo() {
    let that = this;
    if (that.data.detailContent.hmDelSummaryInfo.videoMaterial) {
      wx.showModal({
        content: "该房源已存在视频，重新合成将替换原视频",
        confirmText: "确定替换",
        confirmColor: "#F75353",
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: "/pages/house/RentalHouseDetail/composite/composite?type=video&delId=" +
                that.data.houdelid +
                "&required=0&delType=" +
                this.data.detailContent.houDelVO.delegationType,
            });
          } else if (res.cancel) {}
        },
      });
    } else {
      wx.navigateTo({
        url: "/pages/house/RentalHouseDetail/composite/composite?type=video&delId=" +
          that.data.houdelid +
          "&required=0&delType=" +
          this.data.detailContent.houDelVO.delegationType,
      });
    }
  },

  // 跳转合成视频前校验
  goToVideo() {
    if (this.data.detailContent.hmDelSummaryInfo.videoStatus != 1) {
      this.goTovideo();
    } else {
      wx.showToast({
        title: "视频正在合成中，请稍后再试！",
        icon: "none",
      });
    }
  },

  // 下载房源视频
  downLoadVideo() {
    this.setData({
      videoOption: true,
      // showMoreOptions: true,
      // moreDownload: false,
      // memberOption: false,
    });
  },

  // 下载视频
  handleVideo() {
    let that = this;
    if (that.data.detailContent.hmDelSummaryInfo.videoStatus == 1) {
      wx.showToast({
        title: "视频正在合成中，请稍后再试~",
        icon: "none",
      });
    }

    if (that.data.vrUrl) {
      this.downLoadVideo();
    } else {
      wx.showModal({
        content: "房源视频还未合成，请先合成视频~",
        confirmText: "合成视频",
        confirmColor: "#f64e4e",
        cancelColor: "#ccc",
        success(res) {
          
        },
      });
    }
  },

  // 播放视频
  playVideo() {
    wx.navigateTo({
      url: "/pages/house/RentalHouseDetail/audioPlayPage/audioPlayPage?src=" + this.data.vrUrl,
    });
  },

  // 关闭视频播放
  closeVideo() {
    this.setData({
      videoOption: false,
      // showMoreOptions: false,
    });
  },

  // 下载视频(手机)
  videoDown() {
    let that = this;
    that.setData({
      isLoadingHouse: true,
      videoOption: false,
      // showMoreOptions: false,
    });
    const downloadTask = wx.downloadFile({
      url: that.data.vrUrl,
      success(res) {
        if (res.statusCode === 200) {
          wx.saveVideoToPhotosAlbum({
            filePath: res.tempFilePath,
            success(ress) {
              console.log(ress);
              wx.showToast({
                title: "保存成功",
              });
              api.getMemberPower({
                menuId: that.data.menuId
              }, (res) => {
                if (res.data.isSuccess) {
                  wx.setStorageSync("memberInfo", res.data.content.rows);
                }
              });
            },
            fail(ref) {
              console.log(ref);
            },
          });
        }
      },
    });
    downloadTask.onProgressUpdate((res) => {
      if (res.progress == 100) {
        that.setData({
          isLoadHouseDone: true,
        });
      }
    });
  },

  // 下载视频(pc)
  videoDownPc() {
    let vrUrl = this.data.vrUrl;
    let that = this;
    wx.setClipboardData({
      data: vrUrl,
      success(res) {
        wx.hideToast();
        wx.showModal({
          content: "视频链接已复制，黏贴到电脑端浏览器即可下载到电脑端",
          showCancel: false,
          confirmText: "我知道了",
          success(res) {
            if (res.confirm) {
              api.getMemberPower({
                menuId: that.data.menuId
              }, (res) => {
                if (res.data.isSuccess) {
                  wx.setStorageSync("memberInfo", res.data.content.rows);
                }
              });
              that.closeVideo();
            }
          },
        });
      },
    });
  },

  // 获取视频连接
  getOssfiles() {
    let that = this;
    api.getOssfiles(
      that.data.detailContent.hmDelSummaryInfo.videoMaterial.videoId,
      (res) => {
        that.setData({
          vrUrl: res.data,
          vrTab: that.data.vr ? 1 : 3,
        });
      }
    );
  },

  // 关闭下载视频loading
  handleLoadHouseDone() {
    this.setData({
      isLoadingHouse: false,
      isLoadHouseDone: false,
    });
  },

  // 视频下载超时
  timeoutFn() {
    this.setData({
      isLoadingHouse: false,
    });
    wx.showToast({
      title: "下载视频超时！",
      icon: "none",
    });
  },

  // 复制VR链接
  copyVrUrl() {
    const {
      vrUrl
    } = this.data.detailContent.hmDelSummaryInfo
    wx.setClipboardData({
      data: `${vrUrl}&appName=h5`,
      success(res) {
        wx.showToast({
          title: "VR连接复制成功",
          icon: "none",
        });
      },
    });
  },

  // 下载vr
  vrDownLoad() {
    this.vrdownLoad();
  },

  // 下载vr
  vrdownLoad() {
    api.submitVrTask({
        delId: this.data.houdelid,
      },
      (res) => {
        if (res.data.isSuccess) {
          api.getMemberPower({
            menuId: "f18a0d92aec4499f8866cff3d7226c47"
          }, (res) => {
            if (res.data.isSuccess) {
              wx.setStorageSync("memberInfo", res.data.content.rows);
            }
          });
          this.setData({
            // showMoreOptions: false,
            // memberOption: false,
          });
          wx.showToast({
            title: "VR申请下载成功，预期5分钟后完成下载",
            icon: "none",
          });
          this.getHouseInfo();
        } else {
          wx.showToast({
            title: "VR申请下载失败",
            icon: "none",
          });
          return;
        }
      }
    );
  },

  // 去配音
  goToVoice() {
    // 正在配音则不能重新配音
    if (this.data.detailContent.hmDelSummaryInfo.videoStatus == 1) {
      wx.showToast({
        title: "视频正在合成中，请稍后再试！",
        icon: "none",
      });
      return;
    }
    let that = this;
    if (this.data.detailContent.hmDelSummaryInfo.audioStatus == 0) {
      wx.navigateTo({
        url: "/pages/house/RentalHouseDetail/addAudio/addAudio?required=1&delId=" +
          this.data.houdelid +
          "&delType=" +
          this.data.houseTypes,
      });
    } else {
      wx.showModal({
        content: "该视频已配音，是否需要重新配音",
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: "/pages/house/RentalHouseDetail/addAudio/addAudio?required=1&delId=" +
                that.data.houdelid +
                "&delType=" +
                that.data.houseTypes,
            });
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    }
  },

  // 跳转成全景图的页面
  _goTocomposite() {
    // this.handleHideMoreOptions();
    wx.navigateTo({
      url: "/pages/house/RentalHouseDetail/composite/composite?type=photo&delId=" +
        this.data.houdelid +
        "&menuId=" +
        this.data.menuId +
        "&delType=" +
        this.data.houseTypes,
    });
  },

  // 去合成全景图的页面
  goToComposite() {
    let that = this;
    const { houSubTypeState } = this.data.detailContent.hmDelSummaryInfo
    if (that.data.vr && houSubTypeState == 10) {
      this._goTocomposite();
    } else if (houSubTypeState == 1) {
      wx.showToast({
        title: "VR正在下载中，请待下载完成后再试",
        icon: "none",
      });
    }
  },

  // 跳转全景图的页面
  goTopanoramagram() {
    // this.handleHideMoreOptions();
    wx.navigateTo({
      url: "/pages/house/RentalHouseDetail/panoramagram/panoramagram?delId=" +
        this.data.houdelid +
        "&menuId=" +
        this.data.menuId,
    });
  },

  // 去下载全景图的页面
  goToPanoramagram() {
    let that = this;
    if (that.data.vr && that.data.detailContent.hmDelSummaryInfo.notAvailableScenesNum > 0) {
      this.goTopanoramagram();
    } else if (
      (that.data.vrdown && that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 0) ||
      that.data.detailContent.hmDelSummaryInfo.houSubTypeState == -1
    ) {
      wx.showModal({
        content: "当前房源未下载VR，请先下载VR~",
        confirmText: "下载VR",
        confirmColor: "#f64e4e",
        cancelColor: "#ccc",
        success(res) {
          if (res.confirm) {
            let e = {
              currentTarget: {
                dataset: {
                  id: "f18a0d92aec4499f8866cff3d7226c47"
                }
              },
            };
            that.handleMemberDownLoadImgs(e);
          }
        },
      });
    } else if (that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 1) {
      wx.showToast({
        title: "VR正在下载中，请待下载完成后再试",
        icon: "none",
      });
    } else if (
      that.data.detailContent.hmDelSummaryInfo.houSubTypeState == 10 &&
      that.data.detailContent.hmDelSummaryInfo.notAvailableScenesNum == 0 &&
      (that.data.detailContent.hmDelSummaryInfo.sphereStatus == 0 ||
        that.data.detailContent.hmDelSummaryInfo.sphereStatus == -1)
    ) {
      wx.showModal({
        content: "全景图还未合成，请先合成全景图~",
        confirmText: "去合成",
        confirmColor: "#f64e4e",
        cancelColor: "#ccc",
        success(res) {
          if (res.confirm) {
            let e = {
              currentTarget: {
                dataset: {
                  id: "60e6298af0b24f9db9af005e11e8e87a"
                }
              },
            };
            that.handleMemberDownLoadImgs(e);
          }
        },
      });
    } else if (that.data.detailContent.hmDelSummaryInfo.sphereStatus == 1) {
      wx.showToast({
        title: "全景图正在合成中，请稍后再试~",
        icon: "none",
      });
    }
  },

  // 跳转vr
  goToVr() {
    const {
      vrUrl
    } = this.data.detailContent.hmDelSummaryInfo
    let agentId = getApp().globalData.loginUserInfo.data.content.sessionUser.id;
    app.globalData.vrHouseInfo = {
      ...this.data.detailContent.houDelVO,
      homeImg: this.data.detailContent.houImageVO[0].url,
    };
    if (this.data.detailContent.hmDelSummaryInfo.houSubTypeState == 1) {
      return wx.showToast({
        title: "VR下载未完成，请稍后再试～",
        icon: "none",
      });
    }

    if (vrUrl && httpUrlCheck(vrUrl)) {
      wx.navigateTo({
        url: `/pages/webView/webView?webViewUrl=${vrUrl.replace('?', '&')}&appName=jjrjs`,
      });
    } else {
      wx.showToast({
        title: "VR播放地址不合法～",
        icon: "none",
      });
    }
  },

  // 切换房东弹窗
  changeFormLandlord() {
    if (this.data.isShowFormLandlord) {
      this.data._autoCallLandlordFlag = false
      this.setData({
        currentLandlordInfo: {}
      })
    }
    this.setData({
      isShowFormLandlord: !this.data.isShowFormLandlord
    })
  },

  // 添加/编辑房东成功
  onChangeLandlordSuccess() {
    let flag = this.data._autoCallLandlordFlag
    this.getLandlordPhone()
      .then(() => {
        if (flag) {
          this.onCallLandlord()
        }
      })
    this.changeFormLandlord()
  },

  // 添加/编辑房东取消
  onChangeLandlordFail() {
    this.changeFormLandlord()
  },

  // 编辑房东
  onEditLandlord(e) {
    let currentLandlordInfo = {}
    const {
      landlordList = []
    } = this.data
    landlordList.forEach(item => {
      if (item.id === e.detail) {
        currentLandlordInfo = item
      }
    })
    this.setData({
      currentLandlordInfo
    })
    this.changeFormLandlord()
  },

  // 删除房东
  async onDelLandlord(e) {
    const res = await api.delLandlordPhone(e.detail)
    if (res && res.data && res.data.isSuccess) {
      wx.showToast({
        icon: 'none',
        title: '删除成功',
      })
      this.getLandlordPhone()
    } else {
      wx.showToast({
        icon: 'none',
        title: '删除失败',
      })
    }
  },

  // 获取房东列表
  async getLandlordPhone() {
    return new Promise(async (resolve, reject) => {
      try {
        let delId = this.data.detailContent.houDelVO.id || ''
        const res = await api.getLandlordPhone({
          hmDelId: delId
        })
        if (res && res.data && res.data.content) {
          let landlordList = res.data.content.map(item => {
            return {
              id: item.id || '',
              name: item.phoneOwner || '',
              mobile: item.phoneNumber || '',
              secretMobile: item.phoneNumber ? this.mobileToSecret(item.phoneNumber) : ''
            }
          })
          this.setData({
            landlordList,
          })
          resolve()
        } else {
          reject()
        }
      } catch (error) {
        reject()
        console.log('###err###', error);
      }
    })
  },

  // 手机号转隐藏手机
  mobileToSecret(cellValue) {
    if (Number(cellValue) && String(cellValue).length === 11) {
      var mobile = String(cellValue)
      var reg = /^(\d{3})\d{4}(\d{4})$/
      return mobile.replace(reg, '$1****$2')
    } else {
      return cellValue
    }
  },

  // 联系房东
  onCallLandlord() {
    const {
      landlordList
    } = this.data
    if (landlordList && landlordList.length) {
      const mobileOptions = landlordList.map(item => {
        return `${item.mobile}(${item.name})`
      })
      wx.showActionSheet({
        itemList: mobileOptions,
        success(res) {
          wx.makePhoneCall({
            phoneNumber: landlordList[res.tapIndex].mobile
          })
        },
        fail(res) {}
      })
    } else {
      this.data._autoCallLandlordFlag = true
      this.changeFormLandlord()
    }
  },

  // 添加房源轨迹
  onAddHouseTrack() {
    this.setData({
      isShowFormHouseTrack: true
    })
  },

  // 加载更多房源轨迹
  onMoreHouseTrack() {
    this.getHouseTrack()
  },

  // 获取房源轨迹
  async getHouseTrack() {
    return new Promise(async (resolve, reject) => {
      try {
        let delId = this.data.detailContent.houDelVO.id || ''
        let type = this.data.detailContent.houDelVO.delegationType || ''
        const {
          _trackListIndex,
          _trackListSize,
          isTrackListMore
        } = this.data
        let currentIndex = _trackListIndex + 1
        if (!isTrackListMore) {
          return
        }
        const res = await api.getHouseTrack({
          hmDelId: delId,
          pageNum: currentIndex,
          pageSize: _trackListSize
        })
        if (res && res.data && res.data.content) {
          let result = res.data.content
          let houseTrackList = result.list.map(item => {
            let content = '';
            let title = '';
            if (item.houseTrackCode === 'CHANGE_PRICE') {
              title = '修改价格'
              item.oldPrice = item.oldPrice || 0
              item.nowPrice = item.nowPrice || 0
              let priceDifference = item.oldPrice - item.nowPrice || 0;
              let priceUpDown = priceDifference === 0 ? '调价' : priceDifference > 0 ? '降价' : '涨价';
              let unit = type === 'SALES' ? '万' : '元'
              content = `由${type === 'SALES' ? item.oldPrice / 10000 : item.oldPrice}${unit}修改至${type === 'SALES' ? item.nowPrice / 10000 : item.nowPrice}${unit}，${priceUpDown}${Math.abs(type === 'SALES' ? priceDifference / 10000 : priceDifference)}${unit}`
            }
            if (item.houseTrackCode === 'FOLLOW_UP') {
              title = '跟进'
              content = item.houseTrackContent || ''
            }
            if (item.houseTrackCode === 'UP') {
              title = '房源状态'
              content = '上架'
            }
            if (item.houseTrackCode === 'DOWN') {
              title = '房源状态'
              content = '下架'
            }
            return {
              title,
              time: item.createTime ? util.dateFormat(new Date(item.createTime), "yyyy-MM-dd hh:mm") : '',
              content,
            }
          })
          if (currentIndex === 1) {
            this.data.houseTrackList = [...houseTrackList]
          } else {
            this.data.houseTrackList.push(...houseTrackList)
          }
          this.setData({
            isTrackListMore: currentIndex >= result.pages ? false : true,
            _trackListIndex: currentIndex,
            houseTrackList: this.data.houseTrackList,
          })
          resolve()
        } else {
          reject()
        }
      } catch (error) {
        reject()
        console.log('###err###', error);
      }
    })
  },

  // 取消添加房源轨迹
  onChangeTrackFail() {
    this.setData({
      isShowFormHouseTrack: false
    })
  },

  // 添加房源轨迹成功
  onChangeTrackSuccess() {
    this.setData({
      defaultTabSelect: '', // 不要删 有用
    })
    this.setData({
      isShowFormHouseTrack: false,
      tabSelect: _constant.TAB_MANAGE,
      defaultTabSelect: _constant.TAB_MANAGE,
    })
    this.refreshHouseTrack()
    wx.pageScrollTo({
      selector: '#manage >>> .landlord',
      duration: 500
    })
  },

  // 刷新房源轨迹
  refreshHouseTrack() {
    this.setData({
      _trackListIndex: 0,
      isTrackListMore: true,
    })
    this.getHouseTrack()
  },

  // 合作房源---个人房源--底部操作栏
  getOverAllUserData() {
    api.getOverAllUserData({}, (res) => {
      let userInfo = res.data.content
      this.setData({
        userInfo
      })
    })
  },
  //查看头像
  lookPicture(){
    wx.gio("track", constant.LOOK_PICTURE, {
      [constant.HOUSE_INFO]: '查看头像',
    });
    let pictureUrls = []
    pictureUrls.push(this.data.userInfo.avatar)
    wx.previewImage({
      urls: pictureUrls,
    })
  }

  // 获取粉丝列表
  // getFuns() {
  //   var that = this;
  //   api.getFuns({
  //       delId: that.data.houdelid,
  //     },
  //     (res) => {
  //       that.setData({
  //         funsList: res.data.content,
  //       });
  //     }
  //   );
  // },

  // toggleListTabDialog() {
  //   this.setData({
  //     listTabShowDialog: !this.data.listTabShowDialog,
  //   });
  // },

  // callPhone(e) {
  //   var num = e.currentTarget.dataset.phonenum;
  //   wx.makePhoneCall({
  //     phoneNumber: num,
  //   });
  // },

  // toggleContacTabDialog() {
  //   this.setData({
  //     contactShowDialog: !this.data.contactShowDialog,
  //   });
  // },

  // toggleDialog(e) {
  //   var current = e.currentTarget.dataset.current;
  //   if (!current) {
  //     current = this.data.current;
  //     this.setData({
  //       showDialog: false,
  //     });
  //   } else if (current == this.data.current) {
  //     this.setData({
  //       showDialog: !this.data.showDialog,
  //     });
  //   } else {
  //     this.setData({
  //       showDialog: true,
  //     });
  //   }
  //   if (current) {
  //     this.setData({
  //       current: current,
  //     });
  //   } else {
  //     this.setData({
  //       current: this.data.current,
  //     });
  //   }
  // },

  //跳转小区详情
  // goHousingEstateDetail() {
  //   wx.navigateTo({
  //     url: "/pages/house/housingEstateDetail/housingEstateDetail",
  //   });
  // },

  // 去充值页面
  // goToMemberCentre() {
  //   wx.navigateTo({
  //     url: "/pages/mine/memberCentre/memberCentre",
  //   });
  // },

  //无效房源
  // goFailRoom() {
  //   const id = this.data.detailContent.houDelVO.id;
  //   var that = this;
  //   wx.showModal({
  //     title: "提示",
  //     content: "您确定将该房源标记为无效房源吗",
  //     confirmText: "确定",
  //     cancelText: "取消",
  //     success(res) {
  //       if (res.confirm) {
  //         wx.showLoading({
  //           title: "加载中",
  //         });
  //         api.houseFail(id, {}, (res) => {
  //           wx.hideToast();

  //           var pages = getCurrentPages();
  //           var currPage = pages[pages.length - 1]; //当前页面
  //           var prevPage = pages[pages.length - 2]; //上一个页面
  //           const option = {
  //             type: that.data.houseTypes,
  //           };
  //           wx.navigateBack();
  //           prevPage.backRefash && prevPage.backRefash(option);
  //         });
  //       } else if (res.cancel) {
  //         console.log("用户点击取消");
  //       }
  //     },
  //   });
  // },

  // saveImage(img) {
  //   return new Promise((resolve, reject) => {
  //     wx.getImageInfo({
  //       src: img,
  //       success: function ({
  //         path
  //       }) {
  //         wx.saveImageToPhotosAlbum({
  //           filePath: path,
  //           success: () => {
  //             // console.log("保存海报成功" );
  //             resolve();
  //           },
  //           fail: (err) => {
  //             console.log("保存图片失败", err, path);
  //             resolve();
  //           },
  //         });
  //       },
  //       fail: () => {
  //         console.log("读取图片信息失败", err);
  //         resolve();
  //       },
  //     });
  //   });
  // },

  // 预览名片
  // previewImage: function (e) {
  //   var image = e.currentTarget.dataset.image;
  //   var urls = new Array();
  //   urls.push(image);

  //   wx.previewImage({
  //     urls: urls,
  //   });
  // },

  //复制关键信息及链接
  // goCopy() {
  //   let that = this;
  //   that.setData({
  //     // friendsShowDialog: false,
  //     shareShowDialog: false,
  //   });
  //   let detailContent = this.data.detailContent.houDelVO;
  //   let userid = getApp().globalData.loginUserInfo.data.content.sessionUser.id;

  //   let isVr =
  //     this.data.detailContent.hmDelSummaryInfo.houSubType == 1 &&
  //     this.data.detailContent.hmDelSummaryInfo.houSubTypeState == 10 ?
  //     "VR看房 " :
  //     "";

  //   let _price =
  //     detailContent.totalPrices && detailContent.totalPrices != -1 && detailContent.totalPrices != -0.01 ?
  //     detailContent.delegationType == "SALES" ?
  //     detailContent.totalPrices / 10000 + "万元" :
  //     detailContent.totalPrices + "元/月" :
  //     "未填价格";

  //   let _size = detailContent.buildSize != -1 && detailContent.buildSize ? detailContent.buildSize + "㎡" : "未填面积";
  //   let copyText = isVr + detailContent.resblockName + _price + _size;

  //   var loginUserInfo = getApp().globalData.loginUserInfo;
  //   let message = {
  //     touser: wx.getStorageSync("aldstat_op"),
  //     msgtype: "link",
  //     link: {
  //       title: `【${copyText}】分享链接`,
  //       description: "点击可以分享至朋友圈",
  //       url: `${util.shareUrl}/noauth/hou/RentalHouseDetail?houDelId=${detailContent.id}&userId=${userid}`,
  //       thumb_url: that.data.detailContent.houImageVO.length > 0 ?
  //         that.data.detailContent.houImageVO[0].url : "/images/defaultImgSmall.jpg",
  //     },
  //   };
  //   api.setHouseInfo({
  //       agentid: loginUserInfo.data.content.sessionUser.id,
  //       openid: wx.getStorageSync("aldstat_op"),
  //       message: JSON.stringify(message),
  //     },
  //     (res) => {
  //       console.log("成功发送客服消息", res);

  //       wx.gio("track", constant.SHARE_SUCCESS, {
  //         [constant.ROOMTYPE_VAR]: _map[this.data.detailContent.houDelVO.delegationType],
  //         [constant.SHARETYPE_VAR]: constant.PYQ_SHARE,
  //       });
  //     }
  //   );
  // },

  // 权限校验
  // getMemberPower() {
  //   switch (this.data.menuId) {
  //     case "4c75216b479d4ba894e35e14549ca355":
  //       this.setData({
  //         fn: "下载图片",
  //       });
  //       this.hanldedownLoadImgs();
  //       break;
  //     case "73ed001b790d4d1cb3e1f74a88756669":
  //       this.goTopanoramagram();
  //       break;
  //     case "f18a0d92aec4499f8866cff3d7226c47":
  //       this.vrdownLoad();
  //       break;
  //     case "60e6298af0b24f9db9af005e11e8e87a":
  //       this.goTocomposite();
  //       break;
  //     case "5a634e15be20415c854056e30e49545d":
  //       this.handlevideo();
  //       break;
  //     case "cb97dc7641fc482c805d42f83661c1c0":
  //       this.goTovideo();
  //       break;
  //   }
  // },

});